package org.gitos.cloud.domain.mq;


import org.springframework.amqp.core.*;

/**
 * Created by shizhengchu on 16/3/15.
 */
public class MqTools {

    public static void bindDirect(String queueName, String exchangeName, AmqpAdmin rabbitAdmin) {
        DirectExchange exchange = new DirectExchange(exchangeName);
        Queue queue = new Queue(queueName);
        MqTools.bind(queue, exchange, queueName, rabbitAdmin);
    }

    public static void bindDirect(String queueName, String exchangeName,
                                  Enum<?> routeKey, AmqpAdmin rabbitAdmin) {
        DirectExchange exchange = new DirectExchange(exchangeName);
        Queue queue = new Queue(queueName);
        bind(queue, exchange, routeKey.toString(), rabbitAdmin);
    }

    public static void bind(Queue queue, Exchange exchange, String routeKey, AmqpAdmin rabbitAdmin) {
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareExchange(exchange);
        Binding binding = null;
        if (exchange instanceof DirectExchange) {
            binding = BindingBuilder.bind(queue).to((DirectExchange) exchange)
                    .with(routeKey);
        } else if (exchange instanceof TopicExchange) {
            binding = BindingBuilder.bind(queue).to((TopicExchange) exchange)
                    .with(routeKey);
        } else if (exchange instanceof FanoutExchange) {
            binding = BindingBuilder.bind(queue).to((FanoutExchange) exchange);
        }
        if (binding == null) {
            return;
        }
        rabbitAdmin.declareBinding(binding);
    }
}
